import { type ComputedRef } from 'vue';
import type { ComponentProps, FormProps, FormSchema } from '../types/form';

import { inject, unref, computed } from 'vue';
import { createPlaceholderMessage } from '../helper';
import type { ComponentType, OnchangeArgument } from '../types';
import type { IsInternalInterfaceEnum } from '@/enums/formEnum';

export function useFormItem(props: Recordable) {
  const FormItem = inject<
    | {
      getValues: ComputedRef<{
        field: string;
        model: Recordable<any>;
        values: Recordable<any>;
        schema: FormSchema;
      }>;
      getComponentsProps: ComponentProps;
      getDisable: boolean;
      formProps: FormProps;
      setFormModel: (value: any, isSetVal?: boolean) => void;
      onChange: (value: OnchangeArgument) => void
      onFocus: () => void;
      onBlur: () => void;
      validate: () => void;
      onFormItemConfirm: () => void;
    }
    | undefined
  >('FormItem', undefined);

  const getProps = computed((): { modelValue?: any, disabled?: boolean, isInternalInterface?: IsInternalInterfaceEnum } & ComponentProps => {
    if (FormItem) {
      const getValues = unref(FormItem.getValues);
      const ComponentsProps = unref(FormItem.getComponentsProps);

      /** 针对有默认值的组件, 触发了表单验证 */
      if (props?.value !== undefined && !getValues.model.hasOwnProperty(getValues.field)) {
        FormItem.setFormModel(props.value);
      }

      let placeholder = ''
      const { component, label, rulesMessageJoinLabel } = getValues.schema
      const joinLabel = Reflect.has(getValues.schema, 'rulesMessageJoinLabel')
        ? rulesMessageJoinLabel
        : FormItem.formProps.rulesMessageJoinLabel;
      if (!unref(FormItem.getDisable)) {
        placeholder = unref(FormItem.getComponentsProps)?.placeholder ||
          createPlaceholderMessage(component) + `${joinLabel ? label : ''}`;
      }
      return {
        ...ComponentsProps,
        modelValue: getValues.model[getValues.field],
        disabled: unref(FormItem.getDisable),
        isInternalInterface: getValues.schema.isInternalInterface,
        // clearable: ComponentsProps?.clearable ?? props.clearable,
        placeholder: component === 'Attachment' ? unref(FormItem.getComponentsProps)?.placeholder : placeholder
      };
    }
    return props;
  });

  return {
    component: (FormItem && unref(FormItem.getValues).schema.component) as ComponentType,
    FormItem,
    formProps: FormItem?.formProps,
    getProps,
    setFormModel: (value: any, isSetVal?: boolean) => FormItem && FormItem.setFormModel(value, isSetVal),
    validate: () => FormItem && FormItem.validate()
  };
}
